const QQMapWX = require('../../lib/qqmap-wx-jssdk')
const qqmapsdk = new QQMapWX({
  key: '2TLBZ-F466U-LRSVH-GLTHG-ZXSXK-FIBZH'
})
const citySelector = requirePlugin('citySelector');
const key = '2TLBZ-F466U-LRSVH-GLTHG-ZXSXK-FIBZH';
const referer = '';
const location = JSON.stringify({
  latitude: 39.89631551,
  longitude: 116.323459711
});
const category = '生活服务，娱乐休闲';
const chooseLocation = requirePlugin('chooseLocation');
// pages/map/map.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    words: ['公交车站', '餐饮', '医院', '学校', '景点', '休闲', '娱乐', '电影门'],
    word: '医院',
    address: '株洲云龙万达广场',
    markers: null,
    latitude: '',
    longitude: '',
    windowHeight: '',
    infoTexts: [],
  },
  formSubmit() {
    var _this = this;
    //调用地址解析接口
    qqmapsdk.geocoder({
      //获取表单传入地址
      address: _this.data.address,  //地址参数，例：固定地址，address:  '北京市海淀区彩和坊路海淀西大街74号'
      success: (res: any) => {//成功后的回调
        var res = res.result;
        let location = res.location.lat + ',' + res.location.lng
        _this.setData({
          latitude: res.location.lat,
          longitude: res.location.lng,
        })
        _this.nearby_search(location)
      },
      fail: function (error: any) {
        console.error(error);
      },
      complete: function (res: any) {
        console.log(res);
      }
    })
  },
  nearby_search: function (location: any) {
    var _this = this;
    // 调用接口
    qqmapsdk.search({
      keyword: _this.data.word,  //搜索关键词
      location: location,  //设置周边搜索中心点
      success: (res: any) => { //搜索成功后的回调
        var mks = []
        for (var i = 0; i < res.data.length; i++) {
          mks.push({ // 获取返回结果，放到mks数组中
            title: res.data[i].title,
            id: res.data[i].id,
            latitude: res.data[i].location.lat,
            longitude: res.data[i].location.lng,
            iconPath: "../images/定位.png", //图标路径
            width: 30,
            height: 30,
            _distance: res.data[i]._distance,
            callout: {
              content: res.data[i].title + "\n" + "距离您" + res.data[i]._distance + "m",
              color: '#404040',
              bgColor: '#ffffff',
              borderWidth: 1,
              borderColor: '#8a8a8a',
              fontSize: 14,
              padding: 10,
              borderRadius: 10,
              display: 'ALWAYS'
            }
          })
          if (res.data[i]._distance < 1000) {
            res.data[i].infoTexts = `${res.data[i].title}\n距离您${res.data[i]._distance}m`;
          } else {
            res.data[i].infoTexts = `${res.data[i].title}\n距离您${(res.data[i]._distance / 1000).toFixed(1)}km`;
          }
        }
        _this.setData({ //设置markers属性，将搜索结果显示在地图中
          markers: mks,
          infoTexts: res.data.map((item: any) => {
            if (item._distance < 1000) {
              return `${item.title}\n距离您${item._distance}m`;
            } else {
              return `${item.title}\n距离您${(item._distance / 1000).toFixed(1)}km`;
            }
          }),
        })
      },
      fail: function (res: any) {
        console.log(res);
      },
      complete: function (res: any) {
        console.log(res);
      },
    });
  },
  onwords(e: any) {
    console.log('进入onwords');
    this.setData({
      word: this.data.words[e.currentTarget.dataset.i]
    })
    this.nearby_search(this.data.latitude + "," + this.data.longitude);
  },

  city() {
    wx.navigateTo({
      url: `plugin://citySelector/index?key=2TLBZ-F466U-LRSVH-GLTHG-ZXSXK-FIBZH&referer=Baop&hotCitys=北京,上海,重庆,长沙,杭州,株洲,新疆`,
    })
  },
  location() {
    wx.navigateTo({
      url: `plugin://chooseLocation/index?key=2TLBZ-F466U-LRSVH-GLTHG-ZXSXK-FIBZH&referer=Baop&hotCitys=`
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options: any) {
    let show = true;
    let _this = this;
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        show = false;
        _this.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          word: '北大青鸟'
        })
        let location = res.latitude + ',' + res.longitude;
        _this.nearby_search(location);
      }
    });
    if (show)
      this.formSubmit()

    var windowHeight = wx.getSystemInfoSync().windowHeight
    this.setData({
      windowHeight: (windowHeight - 180) + 'px'
    })
  },


  onShow() {
    const selectedCity = citySelector.getCity();
    const location = chooseLocation.getLocation();
    console.log(location);
    if (selectedCity) {
      this.setData({
        address: selectedCity.fullname
      });
    } else {
      this.setData({
        address: location.name
      });
    }
    this.formSubmit()
  },

  onUnload() {
    citySelector.clearCity();
  },
})